package mall

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/mall"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzmallbrand"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MallBrandEditLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewMallBrandEditLogic - 添加/编辑品牌
func NewMallBrandEditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MallBrandEditLogic {
	return &MallBrandEditLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MallBrandEditLogic) MallBrandEdit(req *types.MallBrandEdit) error {
	// 创建实例
	mallBrandDao := mall.NewMallBrandDao(l.ctx, l.svcCtx)

	// 定义排序
	var sort int64

	// 查询父级排序
	if req.MallBrandSort == 0 {
		brandConditions := make([]predicate.HzMallBrand, 0)
		brandConditions = append(brandConditions, hzmallbrand.DeleteAtIsNil())
		brandConditions = append(brandConditions, hzmallbrand.IDEQ(int(req.MallBrandParentId)))
		first, _ := mallBrandDao.MallBrandConditionsFirst(brandConditions)
		if first != nil {
			sort = first.MallBrandSort
		}
	} else {
		sort = req.MallBrandSort
	}

	// 组装参数
	brandInfo := &ent.HzMallBrand{
		MallBrandIcon:       req.MallBrandIcon,
		MallBrandName:       req.MallBrandName,
		MallBrandURL:        req.MallBrandUrl,
		MallBrandSort:       sort,
		MallBrandSiteID:     req.MallBrandSiteId,
		MallBrandSiteStatus: req.MallBrandSiteStatus,
		MallBrandSiteShow:   req.MallBrandSiteShow,
		BrandCommissionRate: req.BrandCommissionRate,
		MallBrandParentID:   req.MallBrandParentId,
		UpdateAt:            time.Now().Unix(),
	}

	// 新增品牌信息
	if req.Type == constant.Add {
		brandInfo.CreatedAt = time.Now().Unix()
		if err := mallBrandDao.MallBrandCreate(brandInfo, nil); err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("添加品牌失败: %v", err))
		}
	}

	// 编辑品牌信息
	if req.Type == constant.Edit && req.Id != 0 {
		brandInfo.ID = int(req.Id)
		if err := mallBrandDao.MallBrandUpdate(brandInfo, nil); err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("修改品牌失败: %v", err))
		}
	}

	return nil
}
